import MD5 from 'js-md5'
import Vue from 'vue'
import Qs from 'qs'

export default {
  AnonToken: function (timestamp) {
    var key = process.env.KEY
    return '00' + MD5(timestamp + '&' + key).toUpperCase() // 用户登录前
  },
  AuthToken: function (timestamp, userKey) {
    var key = process.env.KEY
    return '00' + MD5(timestamp + '&' + key + '&' + userKey).toUpperCase() // 用户登录前
  },
  getQueryString: function (name) {
    var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i')
    var r = window.location.search.substr(1).match(reg)
    if (r != null) return unescape(r[2]); return null
  },
  // 生成随机串
  randomString: function (len) {
    len = len || 32
    var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
    var maxPos = $chars.length
    var pwd = ''
    for (var i = 0; i < len; i++) {
      pwd += $chars.charAt(Math.floor(Math.random() * maxPos))
    }
    return pwd
  },
  toQueryParams (url) {
    var search = url.replace(/^\s+/, '').replace(/\s+$/, '').match(/([^?#]*)(#.*)?$/) // 提取location.search中'?'后面的部分
    if (!search) {
      return {}
    }
    var searchStr = search[1]
    var searchHash = searchStr.split('&')

    var ret = {}
    for (var i = 0, len = searchHash.length; i < len; i++) { // 这里可以调用each方法
      var pair = searchHash[i]
      if ((pair = pair.split('='))[0]) {
        var key = decodeURIComponent(pair.shift())
        var value = pair.length > 1 ? pair.join('=') : pair[0]

        if (value !== undefined) {
          value = decodeURIComponent(value)
        }
        if (key in ret) {
          if (ret[key].constructor !== Array) {
            ret[key] = [ret[key]]
          }
          ret[key].push(value)
        } else {
          ret[key] = value
        }
      }
    }
    return ret
  },
  delQueStr (url, ref) { // 删除url中某个参数
    // 如果不包括此参数
    if (url.indexOf(ref) === -1) {
      return url
    }
    var arrUrl = url.split('?')
    var base = arrUrl[0]

    var arrParam = arrUrl[1].split('&')

    var index = -1

    for (var i = 0; i < arrParam.length; i++) {
      var paired = arrParam[i].split('=')

      if (paired[0] === ref) {
        index = i
        break
      }
    }

    if (index === -1) {
      return url
    } else {
      arrParam.splice(index, 1)
      return base + '?' + arrParam.join('&')
    }
  },
  defaultShare: function () {

  },
  jssdkwx: function (api, wx, store, callback) {
    var appid = process.env.APPID
    var timestamp = String(parseInt((Number(new Date())) / 1000))
    var sdktoken = this.AnonToken(timestamp)
    var Url = document.location.href
    var noncestring = this.randomString(32)
    api.jssdk({
      token: sdktoken,
      timestamp: timestamp,
      noncestr: noncestring,
      url: Url.split('#')[0]
    }).then(res => {
      console.log(res)
      if (res.status === '200') {
        var sigin = res.data.signature
        store.commit('changeIndexConf', {
          Timestamp: timestamp,
          nonceString: noncestring,
          signature: sigin
        })
        wx.config({
          debug: false,
          appId: appid,
          timestamp: timestamp,
          nonceStr: noncestring,
          signature: sigin,
          jsApiList: ['onMenuShareAppMessage',
            'onMenuShareTimeline',
            'onMenuShareQQ',
            'onMenuShareWeibo',
            'onMenuShareQZone',
            'chooseImage',
            'uploadImage'
          ]
        })
        wx.error((res) => {
          console.log(res.errMsg)
        })
        wx.ready(() => {
          if (callback) {
            callback()
          }
          wx.onMenuShareAppMessage({
            title: store.state.shareTitle, // 分享标题
            desc: store.state.shareDesc,
            link: store.getters.shareLink + '&channel=7',
            imgUrl: store.state.shareImg,
            type: '', // 分享类型,music、video或link，不填默认为link
            dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
            success: function () {
              // 用户确认分享后执行的回调函数
              if (callback === false) {
                Vue.$vux.alert.show({
                  title: '分享失败，请先保存后再分享'
                })
                return
              }
            },
            cancel: function () {
                // 用户取消分享后执行的回调函数
            }
          })
          wx.onMenuShareTimeline({
            title: store.state.shareTitle, // 分享标题
            desc: store.state.shareDesc,
            link: store.getters.shareLink + '&channel=1',
            imgUrl: store.state.shareImg,
            success: function () {
              // 用户确认分享后执行的回调函数
              if (callback === false) {
                Vue.$vux.alert.show({
                  title: '分享失败，请先保存后再分享'
                })
                return
              }
            },
            cancel: function () {
                // 用户取消分享后执行的回调函数
            }
          })
          wx.onMenuShareQQ({
            title: store.state.shareTitle, // 分享标题
            desc: store.state.shareDesc,
            link: store.getters.shareLink + '&channel=3',
            imgUrl: store.state.shareImg,
            success: function () {
              // 用户确认分享后执行的回调函数
              if (callback === false) {
                Vue.$vux.alert.show({
                  title: '分享失败，请先保存后再分享'
                })
                return
              }
            },
            cancel: function () {
                // 用户取消分享后执行的回调函数
            }
          })
          wx.onMenuShareQZone({
            title: store.state.shareTitle, // 分享标题
            desc: store.state.shareDesc,
            link: store.getters.shareLink + '&channel=5',
            imgUrl: store.state.shareImg,
            success: function () {
              // 用户确认分享后执行的回调函数
              if (callback === false) {
                Vue.$vux.alert.show({
                  title: '分享失败，请先保存后再分享'
                })
                return
              }
            },
            cancel: function () {
                // 用户取消分享后执行的回调函数
            }
          })
        })
      }
    })
  },
  refreshShare: function (wx, store, api, contentshare, contentId) {
    var timeStamp = String(parseInt((Number(new Date())) / 1000))
    var tokenval = this.AuthToken(timeStamp, store.state.userkey)
    wx.onMenuShareAppMessage({
      title: store.state.shareTitle, // 分享标题
      desc: store.state.shareDesc,
      link: store.getters.shareLink + '&channel=7',
      imgUrl: store.state.shareImg,
      type: '', // 分享类型,music、video或link，不填默认为link
      dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
      success: function () {
        // 用户确认分享后执行的回调函数
        if (contentshare === true) {
          api.articleshare({
            token: tokenval,
            timestamp: timeStamp,
            userId: store.state.userID,
            postId: contentId
          }).then(res => {
          })
        }
      },
      cancel: function () {
          // 用户取消分享后执行的回调函数
      }
    })
    wx.onMenuShareTimeline({
      title: store.state.shareTitle, // 分享标题
      desc: store.state.shareDesc,
      link: store.getters.shareLink + '&channel=1',
      imgUrl: store.state.shareImg,
      success: function () {
        // 用户确认分享后执行的回调函数
        if (contentshare === true) {
          api.articleshare({
            token: tokenval,
            timestamp: timeStamp,
            userId: store.state.userID,
            postId: contentId
          }).then(res => {
          })
        }
      },
      cancel: function () {
          // 用户取消分享后执行的回调函数
      }
    })
    wx.onMenuShareQQ({
      title: store.state.shareTitle, // 分享标题
      desc: store.state.shareDesc,
      link: store.getters.shareLink + '&channel=3',
      imgUrl: store.state.shareImg,
      success: function () {
        // 用户确认分享后执行的回调函数
        if (contentshare === true) {
          api.articleshare({
            token: tokenval,
            timestamp: timeStamp,
            userId: store.state.userID,
            postId: contentId
          }).then(res => {
          })
        }
      },
      cancel: function () {
          // 用户取消分享后执行的回调函数
      }
    })
    wx.onMenuShareQZone({
      title: store.state.shareTitle, // 分享标题
      desc: store.state.shareDesc,
      link: store.getters.shareLink + '&channel=5',
      imgUrl: store.state.shareImg,
      success: function () {
        // 用户确认分享后执行的回调函数
        if (contentshare === true) {
          api.articleshare({
            token: tokenval,
            timestamp: timeStamp,
            userId: store.state.userID,
            postId: contentId
          }).then(res => {
          })
        }
      },
      cancel: function () {
          // 用户取消分享后执行的回调函数
      }
    })
  },

  isWeixin () { // 判读是否在微信里
    var ua = window.navigator.userAgent.toLowerCase()
    return ua.indexOf('micromessenger') !== -1
  },

  isIOS () {
    var u = window.navigator.userAgent
    return !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)
  },

  isAndroid () {
    var u = window.navigator.userAgent
    return u.indexOf('Android') > -1 || u.indexOf('Linux') > -1
  },
  redirectWx (status) {
    var redirectUrl = localStorage.getItem('wxLastUrl')
    var currentUrl = window.location.href
    if (this.getQueryString('code')) {
      currentUrl = this.delQueStr(currentUrl, 'code')
    }
    if (this.getQueryString('state')) {
      currentUrl = this.delQueStr(currentUrl, 'state')
    }
    var currentStatus = localStorage.getItem('status') || '0'
    if (currentStatus.toString() !== status.toString()) { // 避免死循环
      localStorage.setItem('wxLastUrl', currentUrl)
      redirectUrl = currentUrl
      localStorage.setItem('status', status)
    }
    if (status === true) {
      localStorage.setItem('wxLastUrl', currentUrl)
      redirectUrl = currentUrl
    }
    var params = {
      appid: process.env.APPID,
      redirect_uri: redirectUrl || window.location.href, // process.env.BASE_URL,
      response_type: 'code',
      scope: 'snsapi_userinfo',
      state: 'STATE'
    }
    console.log(Qs.stringify(params))
    window.location.replace('https://open.weixin.qq.com/connect/oauth2/authorize?' + Qs.stringify(params) + '#wechat_redirect')
  },
  setDocumentTitle (name) {
    let UA = navigator.userAgent.toLowerCase()
    let isWeixin = /micromessenger/ig.test(UA)
    window.document.title = Math.random()
    window.document.title = name
    if (isWeixin) {
      let body = document.body
      let iframe = document.createElement('iframe')
      iframe.src = '/favicon.ico'
      iframe.style.display = 'none'
      iframe.onload = () => {
        setTimeout(() => {
          iframe.onload = null
          body.removeChild(iframe)
        }, 0)
      }
      body.appendChild(iframe)
    }
  },
  ipcard (idcard) { // 验证身份证号
    var Errors = [
      '验证通过!',
      '身份证号码位数不对!',
      '身份证号码出生日期超出范围或含有非法字符!',
      '身份证号码校验错误!',
      '身份证地区非法!'
    ]
    var Y, JYM
    var S, M
    var idcardArray = []
    idcardArray = idcard.split('')
    // 地区检验
    if (this.IdCardGetArea(idcard) === false) return Errors[4]
    // 身份号码位数及格式检验
    var ereg
    switch (idcard.length) {
      case 15:
        if ((parseInt(idcard.substr(6, 2)) + 1900) % 4 === 0 || ((parseInt(idcard.substr(6, 2)) + 1900) % 100 === 0 && (parseInt(idcard.substr(6, 2)) + 1900) % 4 === 0)) {
          ereg = /^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}$/ // 测试出生日期的合法性
        } else {
          ereg = /^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}$/ // 测试出生日期的合法性
        }
        if (ereg.test(idcard)) return true
        else return Errors[2]
      case 18:
        if (parseInt(idcard.substr(6, 4)) % 4 === 0 || (parseInt(idcard.substr(6, 4)) % 100 === 0 && parseInt(idcard.substr(6, 4)) % 4 === 0)) {
          ereg = /^[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}[0-9Xx]$/ // 闰年出生日期的合法性正则表达式
        } else {
          ereg = /^[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}[0-9Xx]$/ // 平年出生日期的合法性正则表达式
        }
        if (ereg.test(idcard)) { // 测试出生日期的合法性
          // 计算校验位
          S = (parseInt(idcardArray[0]) + parseInt(idcardArray[10])) * 7 + (parseInt(idcardArray[1]) + parseInt(idcardArray[11])) * 9 + (parseInt(idcardArray[2]) + parseInt(idcardArray[12])) * 10 + (parseInt(idcardArray[3]) + parseInt(idcardArray[13])) * 5 + (parseInt(idcardArray[4]) + parseInt(idcardArray[14])) * 8 + (parseInt(idcardArray[5]) + parseInt(idcardArray[15])) * 4 + (parseInt(idcardArray[6]) + parseInt(idcardArray[16])) * 2 + parseInt(idcardArray[7]) * 1 + parseInt(idcardArray[8]) * 6 + parseInt(idcardArray[9]) * 3
          Y = S % 11
          M = 'F'
          JYM = '10X98765432'
          M = JYM.substr(Y, 1) // 判断校验位
          if (M === idcardArray[17]) return true // 检测ID的校验位
          else return Errors[3]
        } else return Errors[2]
      default:
        return Errors[1]
    }
  },
  IdCardGetArea (idcard) {
    var area = {11: '北京', 12: '天津', 13: '河北', 14: '山西', 15: '内蒙古', 21: '辽宁', 22: '吉林', 23: '黑龙江', 31: '上海', 32: '江苏', 33: '浙江', 34: '安徽', 35: '福建', 36: '江西', 37: '山东', 41: '河南', 42: '湖北', 43: '湖南', 44: '广东', 45: '广西', 46: '海南', 50: '重庆', 51: '四川', 52: '贵州', 53: '云南', 54: '西藏', 61: '陕西', 62: '甘肃', 63: '青海', 64: '宁夏', 65: '新疆', 71: '台湾', 81: '香港', 82: '澳门', 91: '国外'}
    // 地区检验
    if (area[parseInt(idcard.substr(0, 2))] === null) {
      return false
    } else {
      return area[parseInt(idcard.substr(0, 2))]
    }
  }
}
